package com.baiku.sanhos.config;

import com.baiku.sanhos.filter.JwtAuthenticationTokenFilter;
import com.baiku.sanhos.handler.MyAccessDeniedHandlerImpl;
import com.baiku.sanhos.handler.MyAuthenticationEntryPointImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

@Slf4j
@Configuration
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    MyAuthenticationEntryPointImpl myAuthenticationEntryPoint;

    @Autowired
    MyAccessDeniedHandlerImpl myAccessDeniedHandler;

    @Autowired
    SmsSecurityConfigurerAdapter smsSecurityConfigurerAdapter;

    @Autowired
    UsernamePassSecurityConfAdapter usernamePassSecurityConfAdapter;

    // 创建盐值加密
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /*拦截静态资源*/
    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/static/**","/static/img/**","/js/**", "/img/**", "/css/**", "/element/**", "/**/*.js", "/**/*.css");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许 X-Frame-Options 设置为 "SAMEORIGIN"
        http.headers().frameOptions().sameOrigin();

        http.csrf().disable();/*禁用CSRF保护，方便测试*/
        // 不通过session获取SecurityContext
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);  // 添加过滤器

        // 对于登录接口 运行匿名访问
//        http.authorizeRequests()
//                .mvcMatchers("/pa/sends/changeyz","/pa/users/month", "/pa/users/topUp", "/pa/users/changStatus/{id}", "/pa/users/deleteById/{id}", "/pa/users/selectAll", "/pa/users/deleteByIds", "/pa/users/deleteByIds", "/indexasd.html", "/pa/sends/regyz", "/pa/users/login", "/pa/users/reg", "/pa/users/msLogin", "/index.html",
//                        "/pa/sends/yz", "/pa/users/loginOut",
//                        "/pa/doctor/selectByName", "/pa/doctor/SelectDrugNoName","/bindingRecord","/pa/recipe/call","/pa/doctor/changStatus/{id}","/pa/recipe/selectOpenDrug","/pa/recipe/addOpenDrug","/pa/recipe/deleteByIdOpenDrug/{id}",
//                        "/pa/dept/SelectDoctorDept", "/static/**","/pa/doctor/deleteByIds","/pa/dept/selectDict","/pa/doctor/updateById","/pa/doctor/addDoctor","/pa/dept/selectAppoint","/pa/recipe/updateByIdOpenDrug",
//                        "/pa/dept/getDeptDoctor","/pa/dept/selectChild","/pa/dept/deleteByIds","/pa/users/month","/pa/dept/deleteById/{id}","/pa/dept/updateById","/pa/dept/selectByDeptId",
//                        "/pa/drug/selectAll","/pa/drug/deleteDrugId/{id}","/pa/booking/updateByIdStatus/{id}","/pa/booking/deleteByIds","/pa/booking/updateById/{id}","/pa/recipe/call/{id}",
//                        "/pa/recipe/selectRecipeAll",
//                        "/pa/feedback/updateById","/pa/feedback/deleteByIds",//管理员留言反馈模块的请求
//                        "/bgindex.html",//管理员页面
//                        "/pa/drug/selectDrugId/",
//                        "/pa/recipe/selectAdminRecipeAll","/pa/recipe/selectAdminOpenDrug","/pa/recipe/deleteAdminRecipeById/",
//                        "/doctor.html", "doctor.html",//医生
//                        "/reg.html","/login.html",//注册登录
//                        "/", "/pa/dept", "/pa/doctor/queryByParentDeptId/*","/pa/doctor/queryByChildDeptId/*","/beforeIndex/map.html",//首页
//                        "/beforeIndex/alterInformation.html",//首页下拉选项，修改账号信息
//                        "/beforeIndex/selectDrug.html", "/pa/drug",//药价查询
//                        "/beforeIndex/notice.html","/pa/notice/selectOne","/pa/notice/selectTwo",//公告信息？后续改为单个请求
//                        "/beforeIndex/patientsManage.html",//就诊人页面
//                        "beforeIndex/orders.html","/pa/appoint/byDeptId/**","/pa/appoint/byDoctorNo/**","/pa/dept/getDeptIdByDeptName/**",//预约详情页面
//                        "/pa/doctor/queryByDoctorNo/*/ByDate/*","/pa/doctor/queryByDeptId/*/ByDate/*",//根据日期、工号、查看号源
//                        "/beforeIndex/payOrders.html",//缴费订单
//                        "/beforeIndex/registeredManage.html",//预约管理
//                        "/doc.html", "/v2/api-docs", "/swagger-resources", "/favicon.ico"//在线api文档
//                ).permitAll()
//                .and()
//                .authorizeRequests()
//                .antMatchers("/uploads/**","/static/img/**").permitAll() // 放行以/uploads/** 开头的地址
//                .anyRequest().authenticated()// 除上面外的所有请求全部要鉴权认证
//                .and().apply(usernamePassSecurityConfAdapter)
//                .and().apply(smsSecurityConfigurerAdapter)
//                .and().formLogin().loginPage("/login.html");

        http.authorizeHttpRequests().anyRequest().permitAll();

        http.logout()
                .logoutUrl("/pa/users/logout")
                .logoutSuccessUrl("/index.html")/*登出后重定向到首页*/
                .invalidateHttpSession(true) // 是否使HttpSession失效，默认为true
                .deleteCookies("JSESSIONID"); // 删除指定的Cookie，多个Cookie可以用逗号分隔

        System.out.println("进过这里了");

        // 配置异常处理器
        http.exceptionHandling()
                // 配置认证失败处理器
                .authenticationEntryPoint(myAuthenticationEntryPoint);
//                // 配置权限处理器
//                .accessDeniedHandler(myAccessDeniedHandler);
        // 允许跨域
        http.cors();
    }
}
